//
//  MoviePlayerViewController.m
//  Player
//
//  Created by dllo on 15/11/7.
//  Copyright © 2015年 zhaoqingwen. All rights reserved.
//

#import "MoviePlayerViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "AFNetworking.h"
#import "MBProgressHUD+MJ.h"
#import "CFDanmakuView.h"
#import "LXDanMu.h"
#import "UIColor+LX.h"

#define MoviePlayerViewControllerBottomMargin 10
#define kRandomColor [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1]

@interface MoviePlayerViewController () <CFDanmakuDelegate, UITextFieldDelegate>

@property(nonatomic,strong)AVPlayer *player; // 播放属性
@property(nonatomic,strong)AVPlayerItem *playerItem; // 播放属性
@property(nonatomic,assign)CGFloat width; // 坐标
@property(nonatomic,assign)CGFloat height; // 坐标
@property(nonatomic,weak)UISlider *slider; // 进度条
@property(nonatomic,weak)UILabel *currentTimeLabel; // 当前播放时间
@property(nonatomic,weak)UILabel *systemTimeLabel; // 系统时间
@property(nonatomic,weak)UIView *backView; // 上面一层View
@property(nonatomic,assign)CGPoint startPoint;
@property(nonatomic,strong)UISlider *volumeViewSlider;
@property(nonatomic,weak)UIActivityIndicatorView *activity; // 系统菊花
@property(nonatomic,weak)UIProgressView *progress; // 缓冲条
@property(nonatomic,weak)UIView *topView;
@property (nonatomic, strong)NSTimer *timer;
@property (nonatomic, weak) CFDanmakuView *danmakuView; //弹幕视图
@property (nonatomic, weak) UIButton *startBtn;  //播放暂停按钮
@property (nonatomic, weak) UITextField *danmuTextField; //弹幕输入框
@end

@implementation MoviePlayerViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    
    UIInterfaceOrientation ori = [[UIApplication sharedApplication] statusBarOrientation];//获得当前屏幕方向
    if(ori == UIDeviceOrientationLandscapeRight || ori == UIDeviceOrientationLandscapeLeft){
        _width = [[UIScreen mainScreen]bounds].size.width;
        _height = [[UIScreen mainScreen]bounds].size.height;
    }else{
        _width = [[UIScreen mainScreen]bounds].size.height;
        _height = [[UIScreen mainScreen]bounds].size.width;
    }
    
    // 创建AVPlayer
    NSURL *url;
    if (self.video == nil) {
        url = [NSURL fileURLWithPath:self.filePath];
    }else{
        NSString *urlStr = self.video.videourl;
        url = [NSURL URLWithString:urlStr];
    }

    self.playerItem = [AVPlayerItem playerItemWithURL:url];
    self.player = [AVPlayer playerWithPlayerItem:_playerItem];
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    playerLayer.frame = CGRectMake(0, 0, _width, _height);
    [self.view.layer addSublayer:playerLayer];
    [_player play];
    
    //AVPlayer播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:_player.currentItem];
    
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _width, _height)];
    self.backView = backView;
    [self.view addSubview:_backView];
    _backView.backgroundColor = [UIColor clearColor];
    
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _width, _height * 0.15)];
    self.topView = topView;
    _topView.backgroundColor = [UIColor blackColor];
    _topView.alpha = 0.5;
    [_backView addSubview:_topView];
    
    // 监听loadedTimeRanges属性
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    [self createProgress];
    [self createSlider];
    [self createCurrentTimeLabel];
    [self createButton];
    [self backButton];
    [self createTitle];
    [self createMoreBtn];
    [self createGesture];
    [self customVideoSlider];
    
    //系统菊花
    UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    self.activity = activity;
    _activity.center = _backView.center;
    [self.view addSubview:_activity];
    [_activity startAnimating];
    
    //延迟线程
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [UIView animateWithDuration:0.5 animations:^{
            
            _backView.alpha = 0;
        }];
        
    });
    
    //计时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(Stack) userInfo:nil repeats:YES];
    
    if (self.video != nil) {
        //获取弹幕数据
        [self setupDanmakuView];
        
        [self setupDanmakuData];
        
        //视频点击量加1
        [self viewCounts];
        
    }
    
    //监听键盘收回
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBorderDisApper) name:UIKeyboardDidHideNotification object:nil];
    
}

#pragma mark -键盘收回
- (void)keyBorderDisApper
{
    [self hideDanmuTextField];
}

#pragma mark - 视频点击量加1
- (void)viewCounts
{
    //视频播放量加1
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    NSString *url = @"http://cat666.com/cat666-interface/index.php/index/viewcounts";
    
    [mgr POST:url parameters:@{@"id":@(self.video.ID)} success:^(AFHTTPRequestOperation *operation, id response) {
        self.video.viewcounts++;
    } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
        
    }];
}

#pragma mark - 添加弹幕view
- (void)setupDanmakuView
{
    CGRect rect =  CGRectMake(0, 2, self.view.frame.size.height, self.view.frame.size.width-50);
    CFDanmakuView *danmakuView = [[CFDanmakuView alloc] initWithFrame:rect];
    danmakuView.duration = 6.5;
    danmakuView.centerDuration = 2.5;
    danmakuView.lineHeight = 25;
    danmakuView.maxShowLineCount = 15;
    danmakuView.maxCenterLineCount = 5;
    
    danmakuView.delegate = self;
    self.danmakuView = danmakuView;
    
    [self.view addSubview:_danmakuView];
}

#pragma mark - 设置弹幕数据
- (void)setupDanmakuData
{
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    NSString *url = @"http://cat666.com/cat666-interface/index.php/index/getDanmu";
    
    [mgr POST:url parameters:@{@"id":@(self.video.ID)} success:^(AFHTTPRequestOperation *operation, id response) {
        if(response != nil){
            NSArray *arr = response;
            NSMutableArray *danmakus = [NSMutableArray array];
            for (int i=0;i<arr.count;i++) {
                //判断弹幕是否为空字符串
                NSDictionary *dict = arr[i];
                if (![dict[@"danmu"] isEqualToString:@""]) {
                    LXDanMu *danmu = [LXDanMu initWithDict:dict];
                    CFDanmaku *danmaku = [[CFDanmaku alloc] init];

                    NSMutableAttributedString *contentStr = [[NSMutableAttributedString alloc] initWithString:danmu.text attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:danmu.font], NSForegroundColorAttributeName : [UIColor colorWithHexString:danmu.color]}];
                    danmaku.contentStr = contentStr;
                    danmaku.timePoint = danmu.time / 10;
                    danmaku.position = danmu.position;

                    [danmakus addObject:danmaku];
                }
            }
            [self.danmakuView prepareDanmakus:danmakus];
            if (self.danmakuView.isPrepared) {
                [self.danmakuView start];
            }
        }
    } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
        
    }];
}

#pragma mark - 横屏代码
- (BOOL)shouldAutorotate{
    return NO;
} //NS_AVAILABLE_IOS(6_0);当前viewcontroller是否支持转屏

- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    
    return UIInterfaceOrientationMaskLandscape;
} //当前viewcontroller支持哪些转屏方向

-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationLandscapeRight;
}

- (BOOL)prefersStatusBarHidden
{
    return NO; // 返回NO表示要显示，返回YES将hiden
}
#pragma mark - 创建UISlider
- (void)createSlider
{
    UISlider *slider = [[UISlider alloc]init];
    CGFloat sliderW = _width * 0.7;
    CGFloat sliderH = 15;
    CGFloat sliderX = _width * 0.155;
    CGFloat sliderY = _height - sliderH - MoviePlayerViewControllerBottomMargin - 5;
    slider.frame = CGRectMake(sliderX, sliderY, sliderW, sliderH);
    
    slider.minimumTrackTintColor = [UIColor colorWithRed:30 / 255.0 green:80 / 255.0 blue:100 / 255.0 alpha:1];
    slider.maximumValue = 1; //音乐总共时长
    [slider addTarget:self action:@selector(progressSlider:) forControlEvents:UIControlEventValueChanged];
    //[_slider setThumbImage:[UIImage imageNamed:@"ian.png"] forState:UIControlStateNormal];

    self.slider = slider;
    [self.backView addSubview:_slider];
}

#pragma mark - slider滑动事件
- (void)progressSlider:(UISlider *)slider
{
    //拖动改变视频播放进度
    if (_player.status == AVPlayerStatusReadyToPlay) {
        
    //计算出拖动的当前秒数
    CGFloat total = (CGFloat)self.playerItem.duration.value / self.playerItem.duration.timescale;
    
    NSInteger dragedSeconds = floorf(total * slider.value);
    
    //转换成CMTime才能给player来控制播放进度
    CMTime dragedCMTime = CMTimeMake(dragedSeconds, 1);
    
    [_player pause];
    
    [_player seekToTime:dragedCMTime completionHandler:^(BOOL finish){
        
        [_player play];
        
    }];
    
    }
}

#pragma mark - 创建UIProgressView
- (void)createProgress
{
    UIProgressView *progress = [[UIProgressView alloc]init];
    CGFloat progressW = _width * 0.69;
    CGFloat progressH = 15;
    CGFloat progressX = _width * 0.16;
    CGFloat progressY = _height - progressH - MoviePlayerViewControllerBottomMargin;
    progress.frame = CGRectMake(progressX, progressY, progressW, progressH);

    self.progress = progress;
    [_backView addSubview:_progress];
}

#pragma mark - 刷新
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
        CMTime duration = self.playerItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        [self.progress setProgress:timeInterval / totalDuration animated:NO];
    }
}

- (NSTimeInterval)availableDuration
{
    NSArray *loadedTimeRanges = [[_player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
    return result;
}

- (void)customVideoSlider
{
    UIGraphicsBeginImageContextWithOptions((CGSize){ 1, 1 }, NO, 0.0f);
    UIImage *transparentImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    [self.slider setMaximumTrackImage:transparentImage forState:UIControlStateNormal];
}

#pragma mark - 创建播放时间
- (void)createCurrentTimeLabel
{
    UILabel *currentTimeLabel = [[UILabel alloc]init];
    CGFloat currentTimeLabelW = 100;
    CGFloat currentTimeLabelH = 20;
    CGFloat currentTimeLabelX = self.width * 0.86;
    CGFloat currentTimeLabelY = self.height - currentTimeLabelH - MoviePlayerViewControllerBottomMargin - 5;
    currentTimeLabel.frame = CGRectMake(currentTimeLabelX, currentTimeLabelY, currentTimeLabelW, currentTimeLabelH);
    
    currentTimeLabel.textColor = [UIColor whiteColor];
    currentTimeLabel.font = [UIFont systemFontOfSize:12];
    currentTimeLabel.text = @"00:00/00:00";
    
    self.currentTimeLabel = currentTimeLabel;
    [self.backView addSubview:currentTimeLabel];
}

#pragma mark - 计时器事件
- (void)Stack
{
    if (_playerItem.duration.timescale != 0) {
        self.slider.value = CMTimeGetSeconds([_playerItem currentTime]) / (_playerItem.duration.value / _playerItem.duration.timescale);//当前进度
        
        //当前时长进度progress
        NSInteger proMin = (NSInteger)CMTimeGetSeconds([_player currentTime]) / 60;//当前分钟
        NSInteger proSec = (NSInteger)CMTimeGetSeconds([_player currentTime]) % 60;//当前秒
        
        //duration 总时长
        NSInteger durMin = (NSInteger)_playerItem.duration.value / _playerItem.duration.timescale / 60;//当前分钟
        NSInteger durSec = (NSInteger)_playerItem.duration.value / _playerItem.duration.timescale % 60;//当前秒
        self.currentTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld", (long)proMin, (long)proSec, (long)durMin, (long)durSec];
    }
    if (_player.status == AVPlayerStatusReadyToPlay) {
        [_activity stopAnimating];
    } else {
        [_activity startAnimating];
    }
    
}

#pragma mark - 播放和下一首按钮
- (void)createButton
{
    UIButton *startButton = [UIButton buttonWithType:UIButtonTypeCustom];
    CGFloat startButtonW = 28;
    CGFloat startButtonH = startButtonW;
    CGFloat startButtonX = self.width * 0.03;
    CGFloat startButtonY = self.height - startButtonH - MoviePlayerViewControllerBottomMargin;
    startButton.frame = CGRectMake(startButtonX, startButtonY, startButtonW, startButtonH);
    [self.backView addSubview:startButton];
    self.startBtn = startButton;
    
    if (_player.rate == 1.0) {
    
    [startButton setBackgroundImage:[UIImage imageNamed:@"pauseBtn.png"] forState:UIControlStateNormal];
    } else {
        [startButton setBackgroundImage:[UIImage imageNamed:@"playBtn.png"] forState:UIControlStateNormal];

    }
    [startButton addTarget:self action:@selector(startAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //开关弹幕
    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    nextButton.frame = CGRectMake(self.width * 0.09, startButtonY, startButtonW, startButtonW);
    [self.backView addSubview:nextButton];
    [nextButton setBackgroundImage:[UIImage imageNamed:@"open_danmu"] forState:UIControlStateNormal];
    [nextButton setBackgroundImage:[UIImage imageNamed:@"close_danmu"] forState:UIControlStateSelected];
    [nextButton addTarget:self action:@selector(next:) forControlEvents:UIControlEventTouchUpInside];
    nextButton.tag = 1;
}

#pragma mark - 开关弹幕
- (void)next:(UIButton *)btn
{
    btn.tag = btn.tag == 0 ? 1 : 0;
    self.danmakuView.alpha = btn.tag;
    btn.selected = !btn.tag;
}

#pragma mark - 播放暂停按钮方法
- (void)startAction:(UIButton *)button
{
    if (button.selected) {
        [_player play];
        [self.danmakuView start];
        [button setBackgroundImage:[UIImage imageNamed:@"pauseBtn"] forState:UIControlStateNormal];

    } else {
        [_player pause];
        [self.danmakuView pause];
        [button setBackgroundImage:[UIImage imageNamed:@"playBtn"] forState:UIControlStateNormal];

    }
    button.selected =! button.selected;
    
}

#pragma mark - 返回按钮方法
- (void)backButton
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(15, 20, 35, 35);
    [button setBackgroundImage:[UIImage imageNamed:@"iconfont-back.png"] forState:UIControlStateNormal];
    [_topView addSubview:button];
    [button addTarget:self action:@selector(backButtonAction) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - 创建标题
- (void)createTitle
{
    UILabel *label = [[UILabel alloc]init];
    CGFloat labelY = 20;
    CGFloat labelW = self.width * 0.8;
    CGFloat labelH = 30;
    CGFloat labelX = (self.width - labelW) / 2;
    label.frame =CGRectMake(labelX, labelY, labelW, labelH);
    label.text = self.video.fname;
    [_backView addSubview:label];
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
}

#pragma mark - 创建发送弹幕按钮
- (void)createMoreBtn
{
    UIButton *sendDanmuBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sendDanmuBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [sendDanmuBtn setTitle:@"发送弹幕" forState:UIControlStateNormal];
    [sendDanmuBtn setTitleColor:[UIColor grayColor] forState:UIControlStateDisabled];
    [sendDanmuBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [sendDanmuBtn addTarget:self action:@selector(sendDanmu) forControlEvents:UIControlEventTouchUpInside];
    [_backView addSubview:sendDanmuBtn];
    
    if (self.video == nil) {
        sendDanmuBtn.enabled = NO;
    }
    
    CGFloat sendDanmuBtnW = 60;
    CGFloat sendDanmuBtnH = 30;
    CGFloat sendDanmuBtnX = _backView.frame.size.width - sendDanmuBtnW - 5;
    CGFloat sendDanmuBtnY = 20;
    sendDanmuBtn.frame = CGRectMake(sendDanmuBtnX, sendDanmuBtnY, sendDanmuBtnW, sendDanmuBtnH);
    
    /** 弹幕输入框 */
    UITextField *danmuTextField = [[UITextField alloc]init];
    danmuTextField.backgroundColor = [UIColor whiteColor];
    danmuTextField.borderStyle = UITextBorderStyleRoundedRect;
    danmuTextField.delegate = self;
    danmuTextField.returnKeyType = UIReturnKeySend;
    [self.view addSubview:danmuTextField];
    self.danmuTextField = danmuTextField;
    
    CGFloat danmuTextFieldH = 40;
    CGFloat danmuTextFieldY = -40;
    CGFloat danmuTextFieldX = 10;
    CGFloat danmuTextFieldW = self.view.frame.size.height - danmuTextFieldX * 2;
    danmuTextField.frame = CGRectMake(danmuTextFieldX, danmuTextFieldY, danmuTextFieldW, danmuTextFieldH);
}

#pragma mark - 发送弹幕
- (void)sendDanmu
{
    self.startBtn.selected = NO;
    [self startAction:self.startBtn];
    self.startBtn.enabled = NO;
    
    UITextField *danmuTextField = self.danmuTextField;
    [danmuTextField becomeFirstResponder];
    [UIView animateWithDuration:0.5 animations:^{
        CGRect frame = danmuTextField.frame;
        frame.origin.y = 20;
        danmuTextField.frame = frame;
    }];
    
    
}

#pragma mark - 创建手势
- (void)createGesture
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [self.view addGestureRecognizer:tap];
//
//    //获取系统音量
//    MPVolumeView *volumeView = [[MPVolumeView alloc] init];
//    _volumeViewSlider = nil;
//    for (UIView *view in [volumeView subviews]){
//        if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
//            _volumeViewSlider = (UISlider *)view;
//            //NSLog(@"%@",_volumeViewSlider);
//            break;
//        }
//    }
//    _systemVolume = _volumeViewSlider.value;
}

#pragma mark - 轻拍方法
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    if (_backView.alpha == 1) {
        [UIView animateWithDuration:0.5 animations:^{
            
            _backView.alpha = 0;
        }];
    } else if (_backView.alpha == 0){
        [UIView animateWithDuration:0.5 animations:^{
            
            _backView.alpha = 1;
        }];
    }
    if (_backView.alpha == 1) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [UIView animateWithDuration:1 animations:^{
                
                _backView.alpha = 0;
            }];
        });
    }
}
#pragma mark - 滑动调整音量大小
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if(event.allTouches.count == 1){
        //保存当前触摸的位置
        CGPoint point = [[touches anyObject] locationInView:self.view];
        _startPoint = point;
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.timer setFireDate:[NSDate distantFuture]];
    
    if(event.allTouches.count == 1){
        //计算位移
        CGPoint point = [[touches anyObject] locationInView:self.view];
        float dx = point.x - _startPoint.x;
        int index = (int)dx;

        if(index>0){
            if (index % 2 == 0) {
                self.slider.value += 0.02;
            }
        }else{
            if (index % 2 == 0) {
                self.slider.value -= 0.02;
            }
        }
        //亮度调节
        //        [UIScreen mainScreen].brightness = (float) dx/self.view.bounds.size.width;
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self progressSlider:self.slider];
    [self.timer setFireDate:[NSDate date]];
}

- (void)moviePlayDidEnd:(id)sender
{
    [self removeObserver];
    [self dismissViewControllerAnimated:YES completion:^{
    
        
    }];
    
}

- (void)backButtonAction
{
    [self.danmakuView pause];
    [_player pause];

    [self removeObserver];
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}

//移除通知
- (void)removeObserver
{
    [self.timer invalidate];
    self.timer = nil;
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [self.playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}

#pragma mark - 弹幕协议
- (NSTimeInterval)danmakuViewGetPlayTime:(CFDanmakuView *)danmakuView
{
    if(_slider.value == 1.0) [_danmakuView stop];
    
    return CMTimeGetSeconds([_playerItem currentTime]);
}

- (BOOL)danmakuViewIsBuffering:(CFDanmakuView *)danmakuView
{
    return NO;
}

#pragma mark - 键盘代理
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if(userId == nil) {
        [MBProgressHUD showError:@"请先登录再发送弹幕" angle:0];
        [self hideDanmuTextField];
        return NO;
    }
    if ([textField.text isEqualToString:@""]) {
        [MBProgressHUD showError:@"请输入弹幕文字" angle:0];
    }else{
        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
        NSString *danmu = [NSString stringWithFormat:@"{ \"text\":\"%@\",\"color\":\"#ffffff\",\"size\":\"1\",\"position\":\"0\",\"time\":%ld}", textField.text, (long)CMTimeGetSeconds([_player currentTime])];
        
        NSDictionary *dict = @{@"userid":userId, @"videoid":@(self.video.ID), @"danmu":danmu};
        
        [mgr POST:@"http://cat666.com/cat666-interface/index.php/index/sendDanmu" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *dict = responseObject;
            if([dict[@"successed"] integerValue] == 1){
                [MBProgressHUD showSuccess:@"成功发送弹幕" angle:0];
            }else{
                [MBProgressHUD showSuccess:@"发送弹幕失败" angle:0];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [MBProgressHUD showSuccess:@"成功发送弹幕失败" angle:0];
        }];
        
        [self hideDanmuTextField];
    }
    
    return NO;
}

//隐藏弹幕发送框
- (void)hideDanmuTextField
{
    self.startBtn.enabled = YES;
    
    UITextField *danmuTextField = self.danmuTextField;
    [danmuTextField resignFirstResponder];
    [UIView animateWithDuration:0.5 animations:^{
        CGRect frame = danmuTextField.frame;
        frame.origin.y = -40;
        danmuTextField.frame = frame;
    }];
}

@end
